﻿import random
import turtle

width_of_trunk, length, angle = 12, 175, 70
r, g, b = 150, 170, 50
screen = turtle.Screen()


def draw_trunk():
    turtle.left(90)
    turtle.width(width_of_trunk)
    turtle.penup()
    turtle.backward(300)
    turtle.pendown()
    turtle.forward(400)


def draw_leaves(length: int, level: int):
    global r, g, b
    saved_width = turtle.width()
    turtle.width(saved_width * 3.0 / 4.0)
    r += 30
    g += 2
    b += 10
    length = 3.0 / 4.2 * length
    # 分别取r,g,b 变量除255后的余数，使r,g,b均不大于255。rgb 属于[0,255]
    turtle.pencolor(r % 255, g % 255, b % 255)
    turtle.left(angle)
    turtle.forward(length)
    turtle.stamp()

    if level <= width_of_trunk:  # 当树枝层数<=树干宽度时，函数不断调用自身
        draw_leaves(length, level + 1)  # 每次调用都使层数+1
        turtle.back(length)
    turtle.right(2 * angle)
    turtle.forward(length)
    # 如此循环调用直到层数>宽度时，函数停止调用自身，向下运行，并一层层释放堆栈
    if level <= width_of_trunk:
        draw_leaves(length, level + 1)
    turtle.back(length + 4)
    turtle.left(angle)

    turtle.width(saved_width)


def firework(x, y, loop=30, width=2, angle=71):
    turtle.goto(x, y)
    turtle.pendown()
    colors = ['purple', 'yellow', 'blue', 'red', 'orange', 'green']
    for x in range(loop):
        turtle.pencolor(colors[x % 6])
        turtle.width(width)
        turtle.forward(x * 4 / 6 + x)
        turtle.left(angle)
    turtle.penup()


def fireworks(num):
    for i in range(num):
        x = random.randint(-600, 600)
        y = random.randint(-400, 400)
        if i == 6:
            screen.update()
            turtle.bgpic('hand.gif')
        firework(x, y)


if __name__ == '__main__':
    turtle.title('智能时代 逐梦成长')
    turtle.setup(1400, 900)
    turtle.speed(1000)
    turtle.colormode(255)
    turtle.bgcolor('black')
    turtle.pencolor(r, g, b)
    try:
        draw_trunk()
        firework(0, 100, loop=80, width=3, angle=75)
        turtle.home()
        turtle.left(90)
        turtle.width(width_of_trunk)
        turtle.forward(100)
        turtle.pendown()
        turtle.bgpic('blue.gif')
        screen.update()
        draw_leaves(length, level=7)
        turtle.penup()
        screen.update()
        turtle.bgpic('powernet.gif')
        fireworks(9)
        screen.update()
        turtle.bgpic('gate.gif')
        turtle.goto(50, -390)
        turtle.pencolor('red')
        turtle.write('创新争先，团结奋进', font=['宋体', 50, 'bold'])
    except turtle.Terminator:
        print('[Exit by user]')
    else:
        turtle.done()
